<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>单体应用锁及分布式锁 | 王开琦的个人小站</title><meta name="keywords" content="分布式锁"><meta name="author" content="王开琦"><meta name="copyright" content="王开琦"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="在计算机科学中，锁（lock）或互斥（mutex）是一种同步机制，用于在多线程环境中强制对资源的访问进行限制。锁旨在强制实施互斥排它、并发控制策略。单体应用锁只在一个JVM进程中有效，分布式锁是可以跨多个JVM进程的锁。">
<meta property="og:type" content="article">
<meta property="og:title" content="单体应用锁及分布式锁">
<meta property="og:url" content="https://blog.wkq.pub/blog/14-%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84-%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81-%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E4%B8%8E%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/index.html">
<meta property="og:site_name" content="王开琦的个人小站">
<meta property="og:description" content="在计算机科学中，锁（lock）或互斥（mutex）是一种同步机制，用于在多线程环境中强制对资源的访问进行限制。锁旨在强制实施互斥排它、并发控制策略。单体应用锁只在一个JVM进程中有效，分布式锁是可以跨多个JVM进程的锁。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog.wkq.pub/cover/%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.png">
<meta property="article:published_time" content="2022-01-10T12:13:49.000Z">
<meta property="article:modified_time" content="2022-01-15T12:13:49.000Z">
<meta property="article:author" content="王开琦">
<meta property="article:tag" content="单体应用锁">
<meta property="article:tag" content="分布式锁">
<meta property="article:tag" content="并发控制">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog.wkq.pub/cover/%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.png"><link rel="shortcut icon" href="/media/favicon.ico"><link rel="canonical" href="https://blog.wkq.pub/blog/14-%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84-%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81-%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E4%B8%8E%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '单体应用锁及分布式锁',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-01-15 20:13:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/media/top_img2.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">王开琦的个人小站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">单体应用锁及分布式锁</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-01-10T12:13:49.000Z" title="发表于 2022-01-10 20:13:49">2022-01-10</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-01-15T12:13:49.000Z" title="更新于 2022-01-15 20:13:49">2022-01-15</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84/">分布式架构</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/">分布式锁</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="什么是锁"><a href="#什么是锁" class="headerlink" title="什么是锁"></a>什么是锁</h2><h3 id="场景描述"><a href="#场景描述" class="headerlink" title="场景描述"></a>场景描述</h3><p>锁在Java中是一个非常重要的概念，尤其是在当今的互联网时代，高并发的场景下，更是离不开锁。那么锁到底是什么呢？在计算机科学中，锁（lock）或互斥（mutex）是一种同步机制，用于在多线程环境中强制对资源的访问进行限制。锁旨在强制实施互斥排它、并发控制策略。</p>
<p>假设一个场景，大家都去过超市买东西，如果你随身带了包呢，要放到储物柜里 。假如柜子只有一个，现在同时来了3个人A、B、C，都要往这个柜子里放东西。这个场景就是一个多线程场景，多线程自然离不开锁。如下图所示：</p>
<p><img src= "" data-lazy-src="锁在生活中的例子.png" alt=""></p>
<p>A、B、C都要往柜子里面放东西，可是柜子只能放一件东西，那怎么办呢？这个时候就引出了锁的概念，3个人中谁抢到了柜子的锁，谁就可以使用这个柜子，其它的人只能等待。比如：C抢到了锁，C可以使用这个柜子。A和B只能等待，等C使用完了，释放锁之后，A和B再争抢锁，谁抢到了，谁再继续使用柜子。</p>
<h3 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h3><div class="note info simple"><p>将上面的场景反应到程序中，首先创建一个柜子的类：</p>
</div>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cabinet</span> </span>&#123;</span><br><span class="line">    <span class="comment">//柜子存储的数字</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> storeNumber;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getStoreNumber</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> storeNumber;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setStoreNumber</span><span class="params">(<span class="keyword">int</span> storeNumber)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.storeNumber = storeNumber;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note info simple"><p>柜子中存储的是数字。然后将3个用户抽象成一个类：</p>
</div>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="comment">//柜子</span></span><br><span class="line">    <span class="keyword">private</span> Cabinet cabinet;</span><br><span class="line">    <span class="comment">//存储的数字</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> storeNumber;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">(Cabinet cabinet, <span class="keyword">int</span> storeNumber)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cabinet = cabinet;</span><br><span class="line">        <span class="keyword">this</span>.storeNumber = storeNumber;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//使用柜子</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useCabinet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        cabinet.setStoreNumber(storeNumber);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note info simple"><p>在用户的构造方法中，需要传入两个参数，一个是要使用的柜子，另一个是要存储的数字。到这里，柜子和对象已经抽象成了类，接下来再写一个启动类模拟3个用户使用柜子的场景：</p>
</div>
<ul>
<li>首先创建一个柜子的实例，由于场景中只有一个柜子，所以只创建一个柜子实例。</li>
<li>然后创建一个线程池，线程池中有3个线程，每个线程执行一个用户的操作。</li>
<li>每个线程具体的执行过程为：新建用户实例，传入的是用户使用的柜子，由于只有一个柜子，所以传入这个柜子的实例，然后分别传入每个用户要存储的数字，分别是1，2，3，也分别对应着用户A、用户B和用户C。</li>
<li>再调用使用柜子的方法，也就是向柜子中放入要存储的数字，然后立即从柜子中取出数字，并打印出来。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Starter</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Cabinet cabinet = <span class="keyword">new</span> Cabinet();</span><br><span class="line">        ExecutorService executorService = Executors.newFixedThreadPool(<span class="number">3</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= <span class="number">3</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">int</span> storeNumber = i;</span><br><span class="line">            executorService.execute(() -&gt; &#123;</span><br><span class="line">                User user = <span class="keyword">new</span> User(cabinet, storeNumber);</span><br><span class="line">                user.useCabinet();</span><br><span class="line">                System.out.println(<span class="string">&quot;我是用户&quot;</span> + storeNumber + <span class="string">&quot;,我取出的数字是：&quot;</span> + cabinet.getStoreNumber());</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        executorService.shutdown();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note success simple"><p>运行结果1：</p>
</div>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">我是用户2,我取出的数字是：3</span><br><span class="line">我是用户1,我取出的数字是：3</span><br><span class="line">我是用户3,我取出的数字是：3</span><br></pre></td></tr></table></figure>
<div class="note success simple"><p>运行结果2：</p>
</div>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">我是用户1,我取出的数字是：2</span><br><span class="line">我是用户2,我取出的数字是：2</span><br><span class="line">我是用户3,我取出的数字是：2</span><br></pre></td></tr></table></figure>
<p>两次运行的结果不一致，这是因为柜子这个实例没有加锁的缘故，3个用户类并发地向柜子中存储他们的数字，虽然是3个用户并发的操作，但是在具体赋值的时，也是有顺序的，因为变量<code>storeNumber</code>只占有一块内存，<code>storeNumber</code>只存储一个值，存储最后的线程所设置的值。至于那个线程 排在最后，则完全不确定，赋值语句执行完成后，进入到打印语句，打印语句取 <code>storeNumber</code>的值并打印，这时 <code>storeNumber</code>存储的是最后一个线程所设置的值，3个线程取到的值是相同的，就如同上面的打印结果一样。</p>
<p>解决这个问题的关键就是——锁，如果在赋值语句上加上锁，这样当多个线程（本文中的多个用户）同时赋值时，谁抢到了这把锁，谁才能赋值。这样保证同一时刻只能有一个线程进行赋值。</p>
<p>要想打印结果不混乱，还有保证赋值语句和打印语句是原子性的，所以这里使用 <code>synchronized</code> 块，但是 <code>synchronized</code>块里的对象我们使用谁的？<code>user</code>还是<code>cabinet</code> ?当然是 <code>cabinet</code>,因为每个任务都初始化了<code>user</code>，总共有3个 <code>user</code>对象了，而<code>cabinet</code>只有一个，所以<code>synchronized</code>要用cabinet对象。如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span> (cabinet) &#123;</span><br><span class="line">    user.useCabinet();</span><br><span class="line">    System.out.println(<span class="string">&quot;我是用户&quot;</span> + storeNumber + <span class="string">&quot;,我取出的数字是：&quot;</span> + cabinet.getStoreNumber());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note success simple"><p>运行结果3：</p>
</div>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">我是用户1,我取出的数字是：1</span><br><span class="line">我是用户2,我取出的数字是：2</span><br><span class="line">我是用户3,我取出的数字是：3</span><br></pre></td></tr></table></figure>
<div class="note primary simple"><p>由于加入了<code>synchronized</code>块，保证了存储和取出的原子性，这样用户存储的数字和取出的数字就对应上了，不会造成混乱。</p>
</div>
<p><img src= "" data-lazy-src="锁代码图解.png" alt=""></p>
<p>如上图所示，线程A、线程B、线程C同时调用 <code>Cabinet</code>类的<code>setStoreNumber</code>方法，线程B获得了锁，所以线程B可以执行<code>setStoreNumber</code>的方法，线程A和线程C只能等待。</p>
<div class="note default simple"><p><code>synchronized</code>方法，故名思意，是把<code>synchronized</code>关键字写在方法上，它表示这个方法是加了锁的，当多个线程调用这个方法时，只有获得锁的线程才可以执行。</p>
</div>
<div class="note default simple"><p><code>synchronized</code>代码块，需要将加锁的语句都写在 <code>synchronized</code>块内，而在对象锁的位置，需要填写加锁的对象，它的含义是，当多个线程并发执行时，只有获得你写的这个对象的锁，才能执行后面的语句，其它的线程只能等待。<code>synchronized</code>块通常的写法是<code>synchronized(this)</code>，这个<code>this</code>是当前类的实例，也就是说获得当前这个类的对象的锁，才能执行这个方法，这样写的效果和<code>synchronized</code>方法是一样的。</p>
</div>
<h2 id="单体应用锁的局限性"><a href="#单体应用锁的局限性" class="headerlink" title="单体应用锁的局限性"></a>单体应用锁的局限性</h2><div class="note primary no-icon flat"><p><code>synchronized</code>以及<code>Lock</code>锁都是由<code>JDK</code>官方提供的锁的解决方案，也就是说这些锁只能在一个<code>JVM</code>进程内有效，这种锁也叫做单体应用锁。但是，在互联网高速发展的今天，单体应用锁能够满足我们的需求吗？</p>
</div>
<h3 id="互联网架构的演进"><a href="#互联网架构的演进" class="headerlink" title="互联网架构的演进"></a>互联网架构的演进</h3><p>在互联网系统发展之初，系统比较简单，消耗资源小，用户访问量也较少，我们只部署一个<code>Tomcat</code>应用就可以满足需求。系统架构图如下：</p>
<p><img src= "" data-lazy-src="传统单体架构架构图.png" alt=""></p>
<p>一个<code>Tomcat</code>可以看做一个<code>JVM</code>进程,当大量的请求到达系统时，所有的请求都落到这唯一的一个<code>Tomcat</code>上，如果某些请求方法是需要加锁的，比如：秒杀扣减库存，是可以满足需求的。但是随着访问量的增加，导致一个Tomcat难以支撑，这时就需要集群部署<code>Tomcat</code>,使用多个<code>Tomcat</code>共同支撑整个系统。系统架构图如下：</p>
<p><img src= "" data-lazy-src="Tomcat集群架构.png" alt=""></p>
<p>上图中，部署了两个<code>Tomcat</code>，共同支撑系统，当一个请求到达系统时，首先会经过<code>Nginx</code>，<code>Nginx</code>主要是做负载转发的，它会根据自己配置的负载均衡策略将请求转发到其中的一个<code>Tomcat</code>中。当大量请求并发访问时，两个<code>Tomcat</code>共同承担所有的访问量。</p>
<h2 id="分布式锁"><a href="#分布式锁" class="headerlink" title="分布式锁"></a>分布式锁</h2><p>如上所述，在整个系统架构中，存在两个<code>Tomcat</code>，每个<code>Tomcat</code>是一个<code>JVM</code>。在进行秒杀业务的时候，由于大家都在抢购秒杀商品，大量的请求同时到达系统，通过<code>Nginx</code>分发到两个<code>Tomcat</code>。</p>
<p>假设，秒杀商品的数量只有1个，这时，这些大量的请求中，只有一个请求可以成功抢到这个商品，这就需要在扣库存的方法上加锁，扣库存的动作只能一个一个取执行，而不能同时去执行，如果同时执行，这1个商品可能同时被多个人抢到，从而产生超卖现象。这也就是单体应用锁的局限性，它只能在一个<code>JVM</code>内加锁，而不能从这个应用层面去加锁。这个时候就需要使用分布式锁了。</p>
<h3 id="什么是分布式锁"><a href="#什么是分布式锁" class="headerlink" title="什么是分布式锁"></a>什么是分布式锁</h3><p>单体应用锁是在一个<code>JVM</code>进程中有效，无法跨<code>JVM</code>、跨进程。那么分布式锁的定义就出来了，分布式锁就是可以跨域多个<code>JVM</code>、跨越多个进程的锁，这种锁就叫做分布式锁。</p>
<h3 id="分布式锁的设计思路"><a href="#分布式锁的设计思路" class="headerlink" title="分布式锁的设计思路"></a>分布式锁的设计思路</h3><p>由于<code>Tomcat</code>是由<code>Java</code>启动的，所以每个<code>Tomcat</code>可以看成一个<code>JVM</code>，<code>JVM</code>内部的锁是无法跨域多个进程的。所以，要实现分布式锁，只能在<code>JVM</code>之外去寻找，通过其它的组件来实现分布式锁。系统的架构如图所示：</p>
<p><img src= "" data-lazy-src="分布式锁实现架构图.png" alt=""></p>
<p>两个<code>Tomcat</code>通过第三方的组件实现跨<code>JVM</code>、跨进程的分布式锁。这就是分布式锁的解决思路，找到所有<code>JVM</code>可以共同访问的第三方组件，通过第三方组件实现分布式锁。</p>
<h3 id="目前存在的分布式锁的方案"><a href="#目前存在的分布式锁的方案" class="headerlink" title="目前存在的分布式锁的方案"></a>目前存在的分布式锁的方案</h3><p>分布式锁都是通过第三方组件来实现的，目前比较流行的分布式锁解决方案有：</p>
<ul>
<li>数据库，借助数据库可以实现分布式锁，但是在高并发的情况下对数据库的压力较大，所以很少使用。</li>
<li><code>Redis</code>，借助<code>Redis</code>也可以实现分布式锁，而且<code>Redis</code>的<code>Java</code>客户端种类很多，使用的方法也不尽相同。</li>
<li><code>Zookeeper</code>:<code>Zookeeper</code>也可以实现分布式锁，同样<code>Zookeeper</code>也存在多个<code>Java</code>客户端，使用方法也不相同</li>
</ul>
<h2 id="Java中锁的解决方案"><a href="#Java中锁的解决方案" class="headerlink" title="Java中锁的解决方案"></a>Java中锁的解决方案</h2><h3 id="乐观锁与悲观锁"><a href="#乐观锁与悲观锁" class="headerlink" title="乐观锁与悲观锁"></a>乐观锁与悲观锁</h3><div class="note primary simple"><p>更新数据的场景：</p>
</div>
<p>更新数据的主要流程如下：</p>
<ol>
<li>检索出要更新的数据，供操作人员查看；</li>
<li>操作人员更改需要修改的数组；</li>
<li>点击保存，更新数据；</li>
</ol>
<div class="note default simple"><p>这个流程看似简单，但是如果用多线程的思维去思考，就会发现其中隐藏着问题。</p>
</div>
<ol>
<li>A检索出数据；</li>
<li>B检索出数据；</li>
<li>B修改了数据；</li>
<li>A修改数据，系统会修改成功吗？</li>
</ol>
<div class="note default simple"><p>当然啦，A修改成功与否，要看程序怎么写。抛开程序，从常理考虑，A保存数据的时候，系统要给提示，说”你修改的数据已被其他人修改过，请重新查询确认“。那么程序中怎么实现呢？</p>
</div>
<ol>
<li>在检索数据时，将数据的版本号（<code>version</code>）或者最后更新时间一并检索出来；</li>
<li>操作员更改数据以后，点击保存，在数据库执行<code>update</code>操作;</li>
<li>执行<code>update</code>操作时，用步骤1检索出来的版本号或者最后更新时间与数据库中的记录作比较；</li>
<li>如果版本号或最后更新时间一致，则可以更新；</li>
<li>如果不一致，就要给出上面的提示；</li>
</ol>
<div class="note info simple"><p>上述的场景就是 <mark class="hl-label blue">乐观锁</mark>  的实现方式。在<code>Java</code>中乐观锁的并没有确定的方法，或者关键字，它只是一个处理的流程、策略。看懂上面的例子之后，再来看看<code>Java</code>中的乐观锁。</p>
</div>
<p>乐观锁呢，它是假设一个线程在取数据的时候不会被其它线程更改数据，就像上面的例子那样，<mark class="hl-label green">在更新数据的时候会校验数据有没有被修改过</mark> 。它是一种<mark class="hl-label orange">比较交换</mark> 的机制，简称<code>CAS</code>（<code>Compare And Swap</code>）机制。一旦检测到有冲突产生，也就是上面说到的版本号或者最后更新时间不一致，它就会进行重试或者提示，直到没有冲突为止。</p>
<div class="note primary simple"><p>乐观锁的机制如图所示：</p>
</div>
<p><img src= "" data-lazy-src="乐观锁的机制图.png" alt=""></p>
<div class="note primary simple"><p>下面通过程序看一下<code>i++</code>顺序执行的情况。</p>
</div>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Test test = <span class="keyword">new</span> Test();</span><br><span class="line">        <span class="comment">//线程池：50个线程池</span></span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(<span class="number">50</span>);</span><br><span class="line">        <span class="comment">//闭锁</span></span><br><span class="line">        CountDownLatch cdl = <span class="keyword">new</span> CountDownLatch(<span class="number">5000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5000</span>; i++) &#123;</span><br><span class="line">            es.execute(() -&gt; &#123;</span><br><span class="line">                test.i++;</span><br><span class="line">                cdl.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        es.shutdown();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//等待5000个任务执行完成后，打印出执行结果</span></span><br><span class="line">            cdl.await();</span><br><span class="line">            System.out.println(<span class="string">&quot;执行完成后，i&quot;</span> + test.i);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note success simple"><p>上面的程序中，模拟了50个线程同时执行<code>i++</code>，总共执行5000次，按照常规的理解，得到的结果应该是5000，我们运行一下程序，看看执行的结果如何？</p>
</div>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">执行完成后，i&#x3D;4975</span><br><span class="line">执行完成后，i&#x3D;4986</span><br><span class="line">执行完成后，i&#x3D;4971</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>这是我们运行3次后得到的结果，可以看到每次执行的结果都不一样，而且不是5000，这是为什么？这就说明<code>i++</code>并不是一个原子性的操作，在多线程的情况下并不安全。</p>
</div>
<ol>
<li>从内存中取出<code>i</code>的当前值；</li>
<li>将 <code>i</code> 的值加 1；</li>
<li>将计算好的值放入到内存中；</li>
</ol>
<div class="note info simple"><p>这个流程和上面的数据库的操作流程是一样的。在多线程的场景下，我们可以想象一下，线程A和线程B同时从内存取出<code>i</code>的值，假如 i 的值是1000，然后线程A和线程B在同时执行+1的操作，然后把值再放入内存当中，这时，内存中的值是1001，而期望的值是1002，正是这个原因导致了上面的错误。在<code>JDK1.5</code>以后，<code>JDK</code>官方提供了大量的原子类，这些类都是基于<code>CAS</code>机制的，也就是使用了乐观锁。将上面的程序稍微改造一下，如下：</p>
</div>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> AtomicInteger i = <span class="keyword">new</span> AtomicInteger(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Test test = <span class="keyword">new</span> Test();</span><br><span class="line">        <span class="comment">//线程池：50个线程池</span></span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(<span class="number">50</span>);</span><br><span class="line">        <span class="comment">//闭锁</span></span><br><span class="line">        CountDownLatch cdl = <span class="keyword">new</span> CountDownLatch(<span class="number">5000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5000</span>; i++) &#123;</span><br><span class="line">            es.execute(() -&gt; &#123;</span><br><span class="line">                test.i.incrementAndGet();</span><br><span class="line">                cdl.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        es.shutdown();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//等待5000个任务执行完成后，打印出执行结果</span></span><br><span class="line">            cdl.await();</span><br><span class="line">            System.out.println(<span class="string">&quot;执行完成后，i=&quot;</span> + test.i);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>将变量 <code>i</code>  的类型改为 <code>AtomicInteger</code>,<code>AtomicInteger</code>是一个原子类。之前调用 <code>i++</code>的地方改成了 <code>i.incrementAndGet()</code>，<code>incrementAndGet()</code>方法采用了<code>CAS</code>机制,也就是说是用来乐观锁。</p>
</div>
<div class="note success simple"><p>此时运行程序的结果如下：</p>
</div>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">执行完成后，i&#x3D;5000</span><br><span class="line">执行完成后，i&#x3D;5000</span><br><span class="line">执行完成后，i&#x3D;5000</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>同样执行了3次，3 次的结果都是5000，符合预期。这就是乐观锁。对乐观锁稍加总结，乐观锁在读取数据的时候不做任何限制，而是在更新数据的时候，进行数据的比较，保证数据版本一致时再更新数据。 根据它这个特点，可以看出 乐观锁适用于读操作多，而写操作少的场景。</p>
</div>
<div class="note default simple"><p>悲观锁与乐观锁恰恰相反， 悲观锁在读取数据的时候就显示地加锁，直到数据更新完成，释放锁为止。 在这期间只能有一个线程去操作，其它的线程只能等待。在<code>JAVA</code>中悲观锁可以使用<code>synchronized</code>关键字或者<code>ReentrantLock</code>类来实现，还是上面的例子，这里用两种方式来实现一下。</p>
</div>
<div class="tabs" id="悲观锁实现"><ul class="nav-tabs"><li class="tab active"><button type="button" data-href="#悲观锁实现-1">synchronized</button></li><li class="tab"><button type="button" data-href="#悲观锁实现-2">ReentrantLock</button></li></ul><div class="tab-contents"><div class="tab-item-content active" id="悲观锁实现-1"><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Test test = <span class="keyword">new</span> Test();</span><br><span class="line">        <span class="comment">//线程池：50个线程池</span></span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(<span class="number">50</span>);</span><br><span class="line">        <span class="comment">//闭锁</span></span><br><span class="line">        CountDownLatch cdl = <span class="keyword">new</span> CountDownLatch(<span class="number">5000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5000</span>; i++) &#123;</span><br><span class="line">            es.execute(() -&gt; &#123;</span><br><span class="line">                <span class="comment">//修改部分 开始</span></span><br><span class="line">                <span class="keyword">synchronized</span> (test) &#123;</span><br><span class="line">                    test.i++;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">//修改部分 结束</span></span><br><span class="line">                cdl.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        es.shutdown();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//等待5000个任务执行完成后，打印出执行结果</span></span><br><span class="line">            cdl.await();</span><br><span class="line">            System.out.println(<span class="string">&quot;执行完成后，i=&quot;</span> + test.i);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>唯一的改动就是增加了<code>synchronized</code>块，它锁住的对象是<code>test</code>,在所有线程中，谁获得了<code>test</code>对象的锁，谁才能执行<code>i++</code>操作。</p>
</div>

<div class="note success simple"><p>运行结果：</p>
</div>

<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">执行完成后，i&#x3D;5000</span><br><span class="line">执行完成后，i&#x3D;5000</span><br><span class="line">执行完成后，i&#x3D;5000</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>运行3次，结果都是5000，符合预期</p>
</div><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div><div class="tab-item-content" id="悲观锁实现-2"><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">//添加了ReentrantLock</span></span><br><span class="line">    <span class="keyword">private</span> Lock lock = <span class="keyword">new</span> ReentrantLock();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Test test = <span class="keyword">new</span> Test();</span><br><span class="line">        <span class="comment">//线程池：50个线程池</span></span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(<span class="number">50</span>);</span><br><span class="line">        <span class="comment">//闭锁</span></span><br><span class="line">        CountDownLatch cdl = <span class="keyword">new</span> CountDownLatch(<span class="number">5000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5000</span>; i++) &#123;</span><br><span class="line">            es.execute(() -&gt; &#123;</span><br><span class="line">                <span class="comment">//修改部分 开始</span></span><br><span class="line">                test.lock.lock();</span><br><span class="line">                test.i++;</span><br><span class="line">                test.lock.unlock();</span><br><span class="line">                <span class="comment">//修改部分 结束</span></span><br><span class="line">                cdl.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        es.shutdown();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//等待5000个任务执行完成后，打印出执行结果</span></span><br><span class="line">            cdl.await();</span><br><span class="line">            System.out.println(<span class="string">&quot;执行完成后，i=&quot;</span> + test.i);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>在类中显示的增加了 <code>Lock lock = new ReentrantLock</code>;而且在 <code>i++</code>之前增加了<code>lock.lock()</code>加锁操作，在 <code>i++</code>之后增加了<code>lock.unlock()</code>释放锁的操作。同样运行3次。</p>
</div>

<div class="note success simple"><p>运行结果：</p>
</div>

<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">执行完成后，i&#x3D;5000</span><br><span class="line">执行完成后，i&#x3D;5000</span><br><span class="line">执行完成后，i&#x3D;5000</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p>运行3次，结果都是5000，符合预期</p>
</div><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div></div></div>
<div class="note default simple"><p>悲观锁从读取数据的时候就加了锁，并且在更新数据的时候，保证只有一个线程在执行更新操作，没有像乐观锁那样进行数据版本的比较。所以悲观锁适用于读相对少，写相对多的操作。</p>
</div>
<h3 id="公平锁-与-非公平锁"><a href="#公平锁-与-非公平锁" class="headerlink" title="公平锁 与 非公平锁"></a>公平锁 与 非公平锁</h3><p>公平锁和非公平锁是从另一个纬度对锁的分类。从名字不难看出，公平锁在多线程情况下，对待每一个线程都是公平的；而非公平锁恰好与之相反。</p>
<p>举例说明，场景还是去超市买东西，在储物柜存储东西的例子。储物柜只有一个，同时来了3个人使用储物柜，这时A先抢到了柜子，A去使用，B和C自觉进行排队。A使用完之后，后面排队中的第一个人将继续使用柜子，这就是公平锁。在公平锁当中，所有的线程都自觉排队，一个线程执行完以后，排在后面的线程继续使用。</p>
<p>非公平锁则不然，A在使用柜子的时候，B和C并不会排队，A使用完以后，将柜子的钥匙一丢，B和C谁抢到了谁用，甚至可能突然跑来一个D，这个D抢到了钥匙，那么D将使用柜子，这个就是非公平锁。</p>
<div class="tabs" id="公平锁和非公平锁"><ul class="nav-tabs"><li class="tab active"><button type="button" data-href="#公平锁和非公平锁-1">公平锁</button></li><li class="tab"><button type="button" data-href="#公平锁和非公平锁-2">非公平锁</button></li></ul><div class="tab-contents"><div class="tab-item-content active" id="公平锁和非公平锁-1"><p><img src= "" data-lazy-src="公平锁示意图.png" alt=""></p>
<div class="note info simple"><p>多个线程同时执行方法，线程A抢到了锁，A可以执行方法。其它线程则在队列里进行排队，A执行完方法后，会从队列里取出下一个线程B，再去执行方法。以此类推，对于每一个线程来说都是公平的，不会存在后加入的线程先执行的情况。</p>
</div><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div><div class="tab-item-content" id="公平锁和非公平锁-2"><p><img src= "" data-lazy-src="非公平锁示意图.png" alt=""></p>
<div class="note info simple"><p>多个线程同时执行方法，线程A抢到了锁，A可以执行方法。其它线程并没有排队，A执行完方法，释放锁后，其它的线程谁抢到了锁，谁去执行方法。会存在后加入的线程，反而先抢到锁的情况。</p>
</div><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div></div></div>
<div class="note primary simple"><p>公平锁和非公平锁都在<code>ReentrantLock</code>类里给出了实现：</p>
</div>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Creates an instance of &#123;<span class="doctag">@code</span> ReentrantLock&#125;.</span></span><br><span class="line"><span class="comment"> * This is equivalent to using &#123;<span class="doctag">@code</span> ReentrantLock(false)&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ReentrantLock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    sync = <span class="keyword">new</span> NonfairSync();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Creates an instance of &#123;<span class="doctag">@code</span> ReentrantLock&#125; with the</span></span><br><span class="line"><span class="comment"> * given fairness policy.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> fair &#123;<span class="doctag">@code</span> true&#125; if this lock should use a fair ordering policy</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ReentrantLock</span><span class="params">(<span class="keyword">boolean</span> fair)</span> </span>&#123;</span><br><span class="line">    sync = fair ? <span class="keyword">new</span> FairSync() : <span class="keyword">new</span> NonfairSync();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<div class="note default simple"><p><code>ReentrantLock</code>有两个构造方法，默认的构造方法中，<code>sync=new NonfairSync();</code>可以看出它是一个非公平锁。第二个构造方法需要传入一个布尔型的参数，<code>true</code>是公平锁，<code>false</code>是非公平锁。<code>Sync</code> 是<code>ReentrantLock</code>的内部类从上面的源码可以看出<code>sync</code>有两个实现类，分别是<code>FireSync</code> 和  <code>NonfireSync</code>，接下来分别看看获取锁的核心方法。</p>
</div>
<div class="tabs" id="firesync和-nonfiresync"><ul class="nav-tabs"><li class="tab active"><button type="button" data-href="#firesync和-nonfiresync-1">FireSync</button></li><li class="tab"><button type="button" data-href="#firesync和-nonfiresync-2">NonfireSync</button></li></ul><div class="tab-contents"><div class="tab-item-content active" id="firesync和-nonfiresync-1"><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Fair version of tryAcquire.  Don&#x27;t grant access unless</span></span><br><span class="line"><span class="comment"> * recursive call or no waiters or is first.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">tryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Thread current = Thread.currentThread();</span><br><span class="line">    <span class="keyword">int</span> c = getState();</span><br><span class="line">    <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!hasQueuedPredecessors() &amp;&amp;</span><br><span class="line">            compareAndSetState(<span class="number">0</span>, acquires)) &#123;</span><br><span class="line">            setExclusiveOwnerThread(current);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (current == getExclusiveOwnerThread()) &#123;</span><br><span class="line">        <span class="keyword">int</span> nextc = c + acquires;</span><br><span class="line">        <span class="keyword">if</span> (nextc &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">&quot;Maximum lock count exceeded&quot;</span>);</span><br><span class="line">        setState(nextc);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div><div class="tab-item-content" id="firesync和-nonfiresync-2"><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Performs non-fair tryLock.  tryAcquire is implemented in</span></span><br><span class="line"><span class="comment"> * subclasses, but both need nonfair try for trylock method.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">nonfairTryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Thread current = Thread.currentThread();</span><br><span class="line">    <span class="keyword">int</span> c = getState();</span><br><span class="line">    <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (compareAndSetState(<span class="number">0</span>, acquires)) &#123;</span><br><span class="line">            setExclusiveOwnerThread(current);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (current == getExclusiveOwnerThread()) &#123;</span><br><span class="line">        <span class="keyword">int</span> nextc = c + acquires;</span><br><span class="line">        <span class="keyword">if</span> (nextc &lt; <span class="number">0</span>) <span class="comment">// overflow</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">&quot;Maximum lock count exceeded&quot;</span>);</span><br><span class="line">        setState(nextc);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div></div></div>
<div class="note info simple"><p>通过对比两个方法，可以看出唯一的不同之处在于 <code>!hasQueuedPredecessors()</code>这个方法，这很明显是一个队列，由此可以推断出，公平锁是将所有的线程都放在一个队列中，一个线程执行完成后，从队列中取出下一个线程，而非公平锁则没有这个队列。</p>
</div>
<div class="note primary simple"><p>非公平锁是默认的锁的类型，平时使用的也大多是非公平锁。如果使用公平锁，可以在秒杀场景下使用，在秒杀场景下，是遵循先到先得的原则，是需要排队的，所以这种场景下是最适合使用公平锁的。</p>
</div>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81/">单体应用锁</a><a class="post-meta__tags" href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/">分布式锁</a><a class="post-meta__tags" href="/tags/%E5%B9%B6%E5%8F%91%E6%8E%A7%E5%88%B6/">并发控制</a></div><div class="post_share"><div class="social-share" data-image="/cover/%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.png" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/18-分布式架构-分布式协调-Zookeeper简介与环境搭建/" title="Zookeeper简介与环境搭建"><img class="cover" src= "" data-lazy-src="/cover/Zookeeper.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-06</div><div class="title">Zookeeper简介与环境搭建</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">王开琦</div><div class="author-info__description">今日事今日毕</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E9%94%81"><span class="toc-number">1.</span> <span class="toc-text">什么是锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9C%BA%E6%99%AF%E6%8F%8F%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">场景描述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B"><span class="toc-number">1.2.</span> <span class="toc-text">代码示例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E7%9A%84%E5%B1%80%E9%99%90%E6%80%A7"><span class="toc-number">2.</span> <span class="toc-text">单体应用锁的局限性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%92%E8%81%94%E7%BD%91%E6%9E%B6%E6%9E%84%E7%9A%84%E6%BC%94%E8%BF%9B"><span class="toc-number">2.1.</span> <span class="toc-text">互联网架构的演进</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81"><span class="toc-number">3.</span> <span class="toc-text">分布式锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81"><span class="toc-number">3.1.</span> <span class="toc-text">什么是分布式锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E7%9A%84%E8%AE%BE%E8%AE%A1%E6%80%9D%E8%B7%AF"><span class="toc-number">3.2.</span> <span class="toc-text">分布式锁的设计思路</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E5%89%8D%E5%AD%98%E5%9C%A8%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E7%9A%84%E6%96%B9%E6%A1%88"><span class="toc-number">3.3.</span> <span class="toc-text">目前存在的分布式锁的方案</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Java%E4%B8%AD%E9%94%81%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">4.</span> <span class="toc-text">Java中锁的解决方案</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B9%90%E8%A7%82%E9%94%81%E4%B8%8E%E6%82%B2%E8%A7%82%E9%94%81"><span class="toc-number">4.1.</span> <span class="toc-text">乐观锁与悲观锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%AC%E5%B9%B3%E9%94%81-%E4%B8%8E-%E9%9D%9E%E5%85%AC%E5%B9%B3%E9%94%81"><span class="toc-number">4.2.</span> <span class="toc-text">公平锁 与 非公平锁</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="3.数据库-数据库监控与调优-特定语句的原理和调优"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优">3.数据库-数据库监控与调优-特定语句的原理和调优</a><time datetime="2022-04-22T08:14:26.000Z" title="发表于 2022-04-22 16:14:26">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="数据库调优理论"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论">数据库调优理论</a><time datetime="2022-04-22T08:13:31.000Z" title="发表于 2022-04-22 16:13:31">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="慢查询发现与分析"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析">慢查询发现与分析</a><time datetime="2022-04-22T08:12:32.000Z" title="发表于 2022-04-22 16:12:32">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM 调优理论"/></a><div class="content"><a class="title" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论">JVM 调优理论</a><time datetime="2022-04-21T06:40:41.000Z" title="发表于 2022-04-21 14:40:41">2022-04-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="服务治理Eureka"/></a><div class="content"><a class="title" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka">服务治理Eureka</a><time datetime="2022-04-13T13:18:27.000Z" title="发表于 2022-04-13 21:18:27">2022-04-13</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">Copyright© 2022 blog.wkq.pub <span>陇ICP备2021003596号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script></div><div class="aplayer no-destroy" data-id="7675104902" data-server="tencent" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script></div><script src="/live2d_models/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2d_models/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2d_models/assets/penchan.model.json"},"display":{"position":"left","width":100,"height":150,"hOffset":-10,"vOffset":40},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body></html>